package com.renjibo.childred.fragments;


import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.renjibo.childred.R;
import com.renjibo.childred.databases.MySqlite;
import com.renjibo.childred.databases.UserDao;
import com.renjibo.childred.modle.GoodsBean;
import com.renjibo.childred.modle.GoodsChild;
import com.renjibo.childred.modle.ProductInfo;
import com.renjibo.childred.utils.PostHead;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DetailFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DetailFragment extends Fragment implements View.OnClickListener{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    private ViewPager vp;
    private LinearLayout ll_point;
    private TextView gname;
    private TextView mprice;
    private TextView hy_price;
    private EditText count;
    private Button into_shopCar_2;
    private Button keep_it;
    private TextView message_back;
    private List<String> pic;
    private ImageView[] images;
    private ProductInfo.ProductBean product;
    private UserDao userDao;

    public DetailFragment() {

    }


    public static DetailFragment newInstance(String param1, String param2) {
        DetailFragment fragment = new DetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        userDao = new UserDao(new MySqlite(getActivity()));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);
        initView(view);
        return view;
    }
    @Override
    public void onViewCreated(View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //监听
        setClick();
        //请求数据
        getData();

    }
    private void setClick() {
        message_back.setOnClickListener(this);
        into_shopCar_2.setOnClickListener(this);
        keep_it.setOnClickListener(this);
    }

    private void initView(View view) {
        vp = (ViewPager) view.findViewById(R.id.vp);
        //小圆点容器
        ll_point = (LinearLayout) view.findViewById(R.id.ll_point);
        //商品名称
        gname = (TextView) view.findViewById(R.id.gname);
        //市场价格
        mprice = (TextView) view.findViewById(R.id.mprice);
        //会员价
        hy_price = (TextView) view.findViewById(R.id.hy_price);
        //数量
        count = (EditText) view.findViewById(R.id.count);
        //加入购物车
        into_shopCar_2 = (Button) view.findViewById(R.id.into_shopCar_2);
        //收藏
        keep_it = (Button) view.findViewById(R.id.keep_it);
        //返回按钮
        message_back = (TextView) view.findViewById(R.id.message_back);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.message_back://返回
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.into_shopCar_2:
                List<GoodsChild> goodsChildren=new ArrayList<>();
//                boolean childChe, String imageUrl, String name, double price, int num
                    String imageUrl=PostHead.head+ File.separator+product.pic.get(0);
                GoodsChild goodsChild=new GoodsChild(false,imageUrl,product.name,product.comment_count,1);
                goodsChildren.add(goodsChild);
                GoodsBean goodsBean=new GoodsBean("乐哈哈",goodsChildren,false);
                userDao.addUser(goodsBean);

                final AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
                builder.setMessage("添加购物车成功");
                //添加到数据库中

                builder.setPositiveButton("继续购物", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                    }
                });
                builder.setNegativeButton("进入购物车", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getActivity().getSupportFragmentManager().beginTransaction().addToBackStack("nihao").replace(R.id.tabHost,ShoppingFragment.newInstance("","")).commit();
                    }
                });

                builder.show();
                break;
            case R.id.keep_it:
                break;
        }
    }

    //初始化小圆点
    private void initPoint() {
        for (int i = 0; i < pic.size(); i++) {
            ImageView image = new ImageView(getActivity());
            image.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            images[i] = image;
            ll_point.addView(image);
        }
    }
    //请求数据
    public void getData()
    {
        RequestParams params=new RequestParams(mParam1);
        x.http().post(params, new Callback.CommonCallback<String>() {



            @Override
            public void onSuccess(String result) {
                ProductInfo info = PostHead.gson.fromJson(result, ProductInfo.class);
                product = info.product;
                pic = product.pic;
                Log.d("zzz",pic.size()+"图片");
                images = new ImageView[pic.size()];
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                //初始化小圆点
                initPoint();

                setBg(0);

                //设置适配器
                vp.setAdapter(new MyAda());

                vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        setBg(position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });

                gname.setText(product.name);
                mprice.setText("￥"+product.price);
                hy_price.setText("￥"+product.marketprice);
            }
        });
    }
    //设置适配器
    class MyAda extends PagerAdapter {
        @Override
        public int getCount() {
            return pic.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            //动态设置图片
            ImageView image = new ImageView(getActivity());
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            String url="http://120.27.126.103:8080/ECServer_D/";
            x.image().bind(image,url+pic.get(position));
            container.addView(image);
            return image;
        }
    }

    //设置颜色
    public void setBg(int index) {
        for (int j = 0; j < pic.size(); j++) {
            if (j == index) {
                images[j].setImageResource(R.drawable.cicle_image);
            } else {
                images[j].setImageResource(R.drawable.cicle_image_sleect);
            }
        }
    }
}
